<?php

namespace app\admin\controller;

use auth\Auth;
use auth\AuthMenu;
use think\Cache;
use think\Controller;
use think\Request;
use think\Session;

class Base extends Controller
{
    /**
     *初始化函数，包括验证权限、动态读取菜单等
     */
    public function _initialize()
    {
        $userId = session('userInfo.id');

        if (!Session::has('userInfo')) {
            $this->error('请登录后再进行操作！', url('admin/Login/index'));
        }
        $request = Request::instance();
        $m = $request->module();
        $c = $request->controller();
        $a = $request->action();
        //$name = $m . '/' . $c . '/' . $a;
        $path = $m . '/' . str_replace('.', '/', $c) . '/' . $a;
        //p($name);die;
        //p(session('userInfo.id'));
        $auth = new Auth();
        if ($userId != 1) {
            if (!$auth->check($path, $userId)) {
                $this->error('没有该操作权限！', url('admin/Index/index'));
            }
        }

        //根据用户组动态读取缓存菜单，不存在则进行缓存
        $groupInfo = $auth->getGroups($userId);
        $groupId = $groupInfo[0]['group_id'];
        $menuGroup = 'menu_'.$groupId;
        $menu = Cache::get($menuGroup);
        if (!$menu) {
            $authMenu = new AuthMenu();
            $menu = $authMenu->getMenuList($userId);
            Cache::set($menuGroup, $menu);
        }

        $this->assign('menu', $menu);
    }

    /**
     * 从缓存获取活动品牌
     * @return array|mixed
     */
    public function getBrand()
    {
        $project_brand = Cache::get('project_brand');
        if (!$project_brand) {
            $project_brand = db('brand')
                ->column('brand', 'id');
            Cache::set('project_brand', $project_brand);
        }
        return $project_brand;
    }
}
